// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//

package clusterutil

import (
	"regexp"

	"github.com/joomcode/errorx"
	"github.com/kumose/kmopt/pkg/tui"
	"github.com/kumose/kmopt/pkg/utils"
)

var (
	// ErrInvalidClusterName is an error for invalid cluster name. You should use `ValidateClusterNameOrError()`
	// to generate this error.
	ErrInvalidClusterName = errorx.CommonErrors.NewType("invalid_cluster_name", utils.ErrTraitPreCheck)
)

var (
	clusterNameRegexp = regexp.MustCompile(`^[a-zA-Z0-9\-_\.]+$`)
)

// ValidateClusterNameOrError validates a cluster name and returns error if the name is invalid.
func ValidateClusterNameOrError(n string) error {
	if len(n) == 0 {
		return ErrInvalidClusterName.
			New("Cluster name must not be empty")
	}
	if !clusterNameRegexp.MatchString(n) {
		return ErrInvalidClusterName.
			New("Cluster name '%s' is invalid", n).
			WithProperty(tui.SuggestionFromString("The cluster name should only contain alphabets, numbers, hyphen (-), underscore (_), and dot (.)."))
	}
	return nil
}
